//app.js
var util = require('utils/util.js')
var utilMd5 = require('utils/md5.js');
App({
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    var that = this;
    //var logs = wx.getStorageSync('logs') || []
    //logs.unshift(Date.now())
    wx.removeStorageSync('userInfo');
    wx.removeStorageSync('allAbout');
    //底部导航数据
    wx.removeStorageSync('navData0');
    wx.removeStorageSync('navData1');
    //颜色配置信息
    wx.removeStorageSync('color_set');

    // wx.clearStorageSync();
    //登录并获取当前用户信息
    //that.LoginUserInfo();

  },
  //登录并获取当前用户信息
  LoginUserInfo: function (cb, inviteuid = 0) {
    var that = this
    if (!inviteuid || inviteuid == 'undefined') {
      inviteuid = 0;
    }
    //先判断缓存中有无数据
    var userInfo = wx.getStorageSync('userInfo');    
    if (userInfo) {
      that.globalData.userInfo = userInfo;
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {


      // if (new Date().getTime() - parseInt(wx.getStorageSync("lastTime")) < 5000) {
      //   console.log("wx.getUserInfo have execute:");
      //   return;
      // }
      wx.setStorageSync("lastTime", new Date().getTime())
      //调用微信登录接口  
      wx.login({
        success: function (e) {
          wx.getUserInfo({
            success: function (res) {
              console.log(222);
              console.log(res);
              var js_code = e.code;
              console.log("js_code:" + js_code);
              //小程序登录地址
              // var loginUrl = util.api_host + '/index.php?app=w3g&mod=Public&act=loginWechatSmall';
              //会新建用户的 登录请求地址
              // var loginUrl = util.api_host + '/index.php?app=w3g&mod=Public&act=loginWechatSmallCon&binduid=' + util.orgid + '&appid=' + util.appid;
              var loginUrl = util.api_host + '/index.php?app=w3g&mod=Public&act=loginWechatSmallCon&binduid=' + util.orgid;
              var params = {
                "code": js_code,
                "encryptedData": res.encryptedData,
                "iv": res.iv,
                "inviteuid": inviteuid
              };
              console.log("请求地址：" + loginUrl, params);
              wx.request({
                url: loginUrl,
                data: params,
                method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
                // header: {}, // 设置请求的 header
                success: function (response) {
                  console.log(333);
                  console.log(response);
                  if (response.data.status == 1) {
                    //登录成功，存储信息                    
                    that.globalData.userInfo = response.data.data;
                    wx.setStorageSync('userInfo', response.data.data);
                    console.log(that.globalData);
                    typeof cb == "function" && cb(that.globalData.userInfo)

                    // 登录页面
                    if (util.orgid == 13078){ 
                        var path = "/pages/xtt-denglu/xtt-denglu";
                      
                        wx.redirectTo({ 
                          url: path,
                        })
                    } 
                  } else {
                    wx.showToast({
                      title: response.data.message,
                      icon: 'error',
                      duration: 2000
                    })
                  }
                },
                fail: function (e) {
                  // fail
                  console.log("wx.request:", e);
                }
              })
            },
            fail: function(){
              
              // var path = "/pages/authorization/authorization";
              // wx.navigateTo({ 
              //   url: path,
              // })
              console.log("wx.getUserInfo fail:", e);
              typeof cb == "function" && cb(-1);
            }
          })
        },
        fail: function (e) {
          console.log("wx.login fail:", e);
        }
      });
    }
  },

  goAuthorization: function () {
    var path = "/pages/authorization/authorization";
    wx.navigateTo({
      url: path,
    })
  },

  reAuthorize: function (cb) {
    // var that = this;
    wx.openSetting({
      success: function (res) {
        if (res.authSetting["scope.userInfo"]) {
          console.log("reAuthorize success:", res);
          typeof cb == "function" && cb(1);
        } else {
          console.log("reAuthorize fail:", res);
          typeof cb == "function" && cb(-1);
        }
      },
      // fail:function(res){
      //   console.log("reAuthorize fail:", res);
      //   typeof cb == "function" && cb(-1);
      // },
      // complete: function (res) {
      //   if (res.authSetting["scope.userInfo"]) {
      //     console.log("reAuthorize success:", res);
      //     typeof cb == "function" && cb(1);
      //   } else {
      //     console.log("reAuthorize fail:", res);
      //     typeof cb == "function" && cb(-1);
      //   }
      // }
    })
  },

  //获取某个用户id的信息
  GetUserInfo: function(uid, cb) {
    var tc = this.get_tc();
    util.api({
        data: {
          "publickey": util.publiccode,
          "ac": "userinfo",
          "uid": uid,
          //"tc": tc
        },
        success: function (responseData) {
          console.log(responseData);
          var res = responseData.data
           //格式化图片
          if(res.photosData){
            res.photosData = res.photo.split(',');
          }
          //格式化视频
          if (res.videosData) {
            res.videosData = res.video.split(',');
          }
          typeof cb == "function" && cb(res)
        }
      });
  },

  //获取关于  售后保障  联系方式 dataName: about-关于  shouhou-售后  contact-联系方式
  getAllAbout: function (dataName, cb) {
    var allAbout = wx.getStorageSync('allAbout');    
    if (dataName && allAbout){
      var res = allAbout[dataName];
      typeof cb == "function" && cb(res)
    } else {
      util.api({
        data: {
          "publickey": util.publiccode,
          "ac": "about",
          "uid": util.orgid
        },
        success: function (responseData) {
          console.log("所有关于数据：", responseData);
          var allData = responseData.data;
          var res = allData[dataName];
          wx.setStorageSync('allAbout', allData);
          typeof cb == "function" && cb(res)
        }
      });
    }
  },

  //设置语言标识（简体/繁体）标识
  set_tc: function(tc){
    wx.setStorageSync('tc', tc);
    console.log("setStorageSync简体/繁体 tc =" + tc + "!");
  },
  //获取语言（简体/繁体）标识 1:繁体 else 简体
  get_tc: function(){
    var tc = wx.getStorageSync('tc');
    if (util.orgid == 20510&&tc){
      return tc
    }
    console.log("简体/繁体 tc =" + tc + "!");
    if (!tc && -1 != tc) {
      tc = 0;
    } else if (-1 == tc){
      tc = 1;
    }
    console.log("简体/繁体 tc = " + tc); 
    if (util.orgid == 19619 || util.orgid == 20510 || util.orgid == 12545 || util.orgid == 13078 || util.orgid == 14148 || util.orgid == 15938|| util.orgid == 21398){
      tc=1;
      return tc ;
    }
    else{
      return tc;
    }
  },

  //获取底部导航数据
  getBottomNavData: function (path, cb) {
    var that=this;
    var dataKey = 'navData' + this.get_tc();
    //先判断缓存中有无数据
    var navData = wx.getStorageSync(dataKey);
    if (navData) {
      console.log("底部导航数据:", navData);
      navData.forEach(function (m, i) {
        if (m.data.indexOf(path) > 0) {
          m.path = '';
          m.class = 'curr';
          m.img = m.bimage;
          m.color = m.btcolor;
        } else {
          m.img = m.fimage;
          m.color = m.ftcolor;
          m.path = m.data;
        }
        m.text = m.title;
      });
      // 中英切换
      if (util.orgid == 20510) {
        var tc = this.get_tc();
        for (var i = 0; i < navData.length; i++) {
          let navArr = navData[i].title.split(':');          
          navData[i].text = tc == 1 ? navArr[0] : navArr[1];
        }
      }
      typeof cb == "function" && cb(navData);
    } else {
      var params = {
        "publickey": util.publiccode,
        "ac": "getnav",
        "uid": util.orgid,
        "tc": this.get_tc()
      };
      util.api({
        data: params,
        success: function (responseData) {
          console.log("底部导航数据:", responseData);
          var result = responseData.data;
          if (result && result.length > 0) {
            wx.setStorageSync(dataKey, result);
            result.forEach(function (m, i) {
              if (m.data.indexOf(path) > 0) {
                m.path = '';
                m.class = 'curr';
                m.img = m.bimage;
                m.color = m.btcolor;
              } else {
                m.img = m.fimage;
                m.color = m.ftcolor;
                m.path = m.data;
              }
              m.text = m.title;
            });
            // 中英切换
            if (util.orgid == 20510) {
              var tc = that.get_tc();
              for (var i = 0; i < result.length; i++) {
                let navArr = result[i].title.split(':');
                result[i].text = tc == 1 ? navArr[0] : navArr[1];
              }
            }
            typeof cb == "function" && cb(result);
          }
        }
      });
    }
       
  },

  getColorSetData: function(cb){
    // titlebg - 标题栏背景色 titlefont- 标题栏文字色 btnbg- 按钮背景色 btnfont- 按钮字体色 pricecolor- 价格色
    var colorData = wx.getStorageSync("color_set");
    if(colorData){
      typeof cb == "function" && cb(colorData);
    } else {
      var that = this;
      var params = {
        ac: "colorset",
        publickey: util.publiccode,
        uid: util.orgid,
      };
      // console.log("获取视频源地址 参数： ", params);
      util.api({
        data: params,
        success: function (responseData) {
          console.log("获取颜色配置数据： ", responseData);
          var result = responseData.data;
          wx.setStorageSync("color_set", result);
          typeof cb == "function" && cb(result);
        }
      });
    }
  },

  //获取是否显示广告的标记
  getShowGuanggaoSign: function(key, maxCount){
    var date = new Date();
    var day = date.getDate();
    var time = parseInt(date.getTime() / 1000);
    var lastShowInfo = wx.getStorageSync(key, '');
    console.log("原广告显示记录：dis seconds = " + (time - lastShowInfo.time), lastShowInfo);
    if (!lastShowInfo || lastShowInfo.day != day 
      || (lastShowInfo.count < maxCount //今天还有显示次数
      && time - lastShowInfo.time >= 7200)){//并间隔两小时才显示
      return true;
    } else {
      return false;
    }
  },

  //设置最后一次显示广告的标记
  setShowGuanggaoSign: function (key) {
    var date = new Date();
    var day = date.getDate();
    var time = parseInt(date.getTime() / 1000);
    var lastShowInfo = wx.getStorageSync(key, '');
    if(!lastShowInfo){
      lastShowInfo = {};
    }
    var count = 1;
    if(lastShowInfo.day == day){
      count = lastShowInfo.count + 1;
    }
    lastShowInfo.day = day;
    lastShowInfo.time = time;
    lastShowInfo.count = count;
    console.log("设置广告显示记录：", lastShowInfo);
    wx.setStorage({
      key: key,
      data: lastShowInfo
    })
  },


  //计算两个经纬度点的距离
  getDistance: function (lat1, lng1, lat2, lng2) {
    lat1 = lat1 || 0;
    lng1 = lng1 || 0;
    lat2 = lat2 || 0;
    lng2 = lng2 || 0;

    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;

    var r = 6378137;
    return r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)))
  },

  //获取腾讯视频 源链接
  getVideoSrcLink: function (index, videoLink, cb) {
    var that = this;
    var params = {
      ac: "xcxvideo",
      publickey: util.publiccode,
      url: videoLink
    };
    // console.log("获取视频源地址 参数： ", params);
    util.api({
      data: params,
      success: function (responseData) {
        console.log("获取视频源地址 返回： ", responseData);
        if (responseData.data.res) {
          typeof cb == "function" && cb(responseData.data.url, index)
        } else {
          typeof cb == "function" && cb(-1, -1)
        }
      }
    });
  },

  //保存 模版消息 的推送 formid
  saveFormId: function (formid) {
    this.LoginUserInfo(function (res) {
      if (res == -1) {//授权失败 无法上传formId
        return;
      }
      var privateKey = utilMd5.hexMD5(res.uid + 'addformid' + res.token);
      util.api({
        method: "POST",
        data: {
          "privatekey": privateKey,
          "ac": "addformid",
          "uid": res.uid,
          "formid": formid
        },
        success: function (responseData) {
          var res = responseData.data;
        }
      });

    });
  },

  globalData: {
    userInfo: null,
    imgDomain: util.api_host + '/wechat',
    indexshow: true
  },
  
  //消息提示
  dialog: function(title, icon, cb) {
    wx.showToast({
      title: title,
      icon: icon,
      duration: 2000
    });
    setTimeout(function(){
      wx.hideToast()
    }, icon =='success' ? 2000:1000)
    typeof cb == "function" && cb()
  },

  //消息提示
  dialogToast: function (title, icon, cb) {
    wx.showToast({
      title: title,
      icon: icon,
      duration: 1500
    });
    setTimeout(function () {
      typeof cb == "function" && cb()
    }, 1500)

  },

  parseHTMLText: function (htmlSrc) {
    if (!htmlSrc && htmlSrc.length <= 0) return '';

    var str = htmlSrc.length > 300 ? htmlSrc.substring(0, 300) : htmlSrc;
    str = str.replace(/[\r\n]/g, '');
    // console.log("替换<br>后：" + str);

    str = str.replace(/^\s+|\s+$/g, '');     //去掉首尾多余的换行
    // console.log("替换<br>后：" + str);

    str = str.replace(/<br>/g, '\n'); //替换 <br> 为 \n
    // console.log("替换<br>后：" + str);

    str = str.replace(/<br\/>/g, '\n'); //替换 <br> 为 \n
    str = str.replace(/<br \/>/g, '\n'); //替换 <br> 为 \n
    // console.log("替换<br>后：" + str);

    str = str.replace(/<\/?[^>]*>/g, ''); //去除HTML tag
    // console.log("去除HTML tag：" + str);

    str = str.replace(/[ | ]*\n/g, '\n'); //去除行尾空白
    // console.log("去除行尾空白：" + str);

    // str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
    // console.log("去除多余空行：" + str);

    str = str.replace(/&nbsp;/ig, '');//去掉&nbsp;
    // console.log("去掉&nbsp：" + str);

    str = str.replace(/&mdash;/ig, '');//去掉&mdash;
    // console.log("去掉&mdash：" + str);

    // str = str.replace(/\s/g, ''); //将空格去掉
    // console.log("将空格去掉：" + str);
    return str;
  },

  debug: true
})